import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/foundation.dart";
import "package:flutter/material.dart";
import "package:flutter/services.dart";

class Floors extends StatefulWidget {
  final List<Map> floors;
  final void Function(List<Map> value) onChanged;

  const Floors({super.key, required this.floors, required this.onChanged});

  @override
  State<Floors> createState() => _FloorsState();
}

class _FloorsState extends State<Floors> {
  final ScrollController _controller = ScrollController();

  List<Map> get _floors => widget.floors;

  void _handleChanged(int index, String field, int? value) {
    List<Map> next = List.from(_floors);
    next[index][field] = value;
    widget.onChanged(next);
  }

  List<Widget> _renderItem(String label, int index, Map data, String field) {
    Color color = ThemeVars.colorBorder;
    int? value = data[field];
    if (field == "floor" &&
        value != null &&
        _floors.any((ele) => !mapEquals(ele, data) && ele[field] == value)) {
      color = ThemeVars.colorError;
    }
    InputBorder border =
        OutlineInputBorder(borderSide: BorderSide(color: color));
    return [
      Text(label),
      const SizedBox(width: 10),
      Expanded(
        child: TextField(
          controller: TextEditingController(text: value?.toString()),
          decoration: InputDecoration(
            counterText: "",
            border: border,
            enabledBorder: border,
            focusedBorder: border,
            hintText: "请输入",
          ),
          inputFormatters: [FilteringTextInputFormatter.digitsOnly],
          maxLength: 2,
          textAlign: TextAlign.center,
          onChanged: (value) =>
              _handleChanged(index, field, int.tryParse(value)),
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scrollbar(
      controller: _controller,
      child: ListView.separated(
        itemCount: _floors.length,
        itemBuilder: (context, index) {
          Map ele = _floors[index];
          return Container(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 8),
            height: 48,
            decoration: const BoxDecoration(color: Colors.white),
            child: Row(
              children: [
                ..._renderItem("所在楼层", index, ele, "floor"),
                const SizedBox(width: 20),
                ..._renderItem("房间数", index, ele, "room"),
              ],
            ),
          );
        },
        separatorBuilder: (context, index) => const SolidDivider(),
      ),
    );
  }
}
